<script setup lang="ts">
import { useAuthStore } from '@/stores/auth'
import { onMounted, ref, onUnmounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import AppHeader from '@/components/layout/AppHeader.vue'
import NotificationModal from '@/components/common/NotificationModal.vue'

import { useGiftEffects } from '@/utils/useGiftEffects'
import { api, API_BASE_URL, toAbsoluteUrl } from '@/utils/request'

const auth = useAuthStore()
const router = useRouter()
const route = useRoute()

const liveRoom = ref<any>(null)
const loading = ref(false)
const messages = ref<any[]>([])
const messageInterval = ref<any>(null)
const messagesContainer = ref<HTMLElement | null>(null)
const messageRounds = ref(0) // 记录已发送的轮数
const currentPresetIndex = ref(0) // 当前预设消息的索引

// 聊天输入
const inputText = ref('')

// 试看相关（无积分）
const trialCountdown = ref<number>(0)
const trialActive = ref<boolean>(false)
const trialTimer = ref<any>(null)

// 有积分用户观看状态
const hasPoints = ref<boolean>(false)
const canEndWatching = ref<boolean>(false)

// 通知弹窗状态
const showNotificationModal = ref<boolean>(false)
const notificationTitle = ref<string>('알림')
const notificationMessage = ref<string>('코인부족으로 라이브 입장이 불가합니다')

// 移除礼物选择相关变量，只保留礼物展示

// 手动观看统计
const onlineCount = ref(0)
// Live SSE for gifts and messages
let liveEs: EventSource | null = null
const { trigger: triggerEffect } = useGiftEffects()
function connectLiveSSE() {
  if (!route.params.id) return
  liveEs = new EventSource(`${API_BASE_URL}/api/live/rooms/${route.params.id}/stream`)

  // 监听礼物消息
  liveEs.addEventListener('gift', (ev: MessageEvent) => {
    try {
      const data = JSON.parse(ev.data || '{}')
      // 添加礼物消息到聊天
      messages.value.push({
        id: data.id || Date.now(),
        content: data.content,
        username: data.username,
        avatar: data.avatar,
        timestamp: new Date(data.timestamp),
        isGift: true
      })
      scrollToBottom()

      // 触发礼物特效
      const preset = data.giftEffectPreset || 'burst'
      triggerEffect(preset as any, Number(data.quantity || 1))
    } catch {}
  })

  // 监听用户聊天消息
  liveEs.addEventListener('message', (ev: MessageEvent) => {
    try {
      const data = JSON.parse(ev.data || '{}')
      messages.value.push({
        id: data.id || Date.now(),
        content: data.content,
        username: data.username,
        avatar: data.avatar,
        timestamp: new Date(data.timestamp),
        senderUserId: data.senderUserId,
        isUserMessage: data.isUserMessage
      })
      scrollToBottom()
    } catch {}
  })
}

const heartbeatTimer = ref<any>(null)
const HEARTBEAT_INTERVAL_MS = 30000

onMounted(async () => {
  // 确保用户状态完整
  const isLoggedIn = await auth.ensureUserState()
  if (!isLoggedIn) {
    router.replace('/login')
    return
  }

  // 检查积分余额，决定是否启动10秒倒计时
  try {
    const res = await api.get('/api/pay/wallet')
    if (res.ok) {
      const data = await res.json()
      const balance = BigInt(String(data?.balancePoints ?? '0'))
      hasPoints.value = balance > BigInt(0)
      if (!hasPoints.value) {
        // 无积分：启动10秒试看倒计时
        startTrialCountdown()
      } else {
        // 有积分：可以正常观看，显示结束观看按钮
        canEndWatching.value = true
      }
    }
  } catch {}

  await fetchLiveRoom()
  startMessageSimulation()
  startHeartbeat()
  connectLiveSSE()
})

onUnmounted(() => {
  if (messageInterval.value) {
    clearInterval(messageInterval.value)
  }
  stopHeartbeat()
  if (liveEs) {
    liveEs.close()
    liveEs = null
  }
})

const fetchLiveRoom = async () => {
  loading.value = true
  try {
    const response = await api.get(`/api/live/rooms/${route.params.id}`)

    // 检查是否是403错误（试看结束或其他权限问题）
    if (response.status === 403) {
      const errorData = await response.json().catch(() => ({}))
      const errorMessage = errorData?.error || 'ALL부족으로 라이브 시청이 불가합니다'

      // 如果是试看相关的错误，显示自定义弹窗
      if (errorMessage.includes('체험 시청이 종료되었습니다') ||
          errorMessage.includes('시청이 종료되었습니다') ||
          errorMessage.includes('ALL부족')) {
        notificationMessage.value = '코인부족으로 라이브 입장이 불가합니다'
        showNotificationModal.value = true
        return
      }
    }

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`)
    }

    const data = await response.json()
    liveRoom.value = data

    // 设置手动观看数
    onlineCount.value = data.manualViewerCount || 0

    // 不再初始化显示系统消息，只保留空的消息数组
    messages.value = []
  } catch (error) {
    console.error('라이브 방 상세 정보 가져오기 실패:', error)
    router.push('/live')
  } finally {
    loading.value = false
  }
}

const startMessageSimulation = () => {
  // 模拟消息滚动，把预设消息全部发3轮
  messageInterval.value = setInterval(() => {
    if (messageRounds.value >= 3) {
      // 达到3轮后停止发送消息
      if (messageInterval.value) {
        clearInterval(messageInterval.value)
        messageInterval.value = null
      }
      return
    }

    if (liveRoom.value?.presets && liveRoom.value.presets.length > 0) {
      const presets = liveRoom.value.presets
      const currentPreset = presets[currentPresetIndex.value]
      const usernames = ['귀여운이', '라이브팬', '시청자A', '관객123', '올빼미', '팬클럽']
      const randomUsername = usernames[Math.floor(Math.random() * usernames.length)]

      messages.value.push({
        id: Date.now(),
        content: currentPreset.content,
        username: randomUsername,
        avatar: `https://picsum.photos/32?random=${Date.now()}`,
        timestamp: new Date(),
        isSystem: false
      })

      // 移动到下一个预设消息
      currentPresetIndex.value++
      if (currentPresetIndex.value >= presets.length) {
        // 一轮结束，开始下一轮
        currentPresetIndex.value = 0
        messageRounds.value++
      }

      // 保持消息列表不超过50条
      if (messages.value.length > 50) {
        messages.value = messages.value.slice(-50)
      }

      // 自动滚动到底部
      scrollToBottom()
    }
  }, 2000 + Math.random() * 3000) // 2-5秒随机间隔
}


function startTrialCountdown() {
  stopTrialCountdown()
  trialActive.value = true
  trialCountdown.value = 10
  // 无积分试用期，将心跳频率提至1秒以便后端累计watchSeconds并在10秒后标记结束
  if (heartbeatTimer.value) {
    clearInterval(heartbeatTimer.value)
    heartbeatTimer.value = setInterval(sendHeartbeat, 1000)
  }
  trialTimer.value = setInterval(() => {
    trialCountdown.value -= 1
    if (trialCountdown.value <= 0) {
      stopTrialCountdown()
      showNotificationModal.value = true
    }
  }, 1000)
}
function stopTrialCountdown() {
  if (trialTimer.value) {
    clearInterval(trialTimer.value)
    trialTimer.value = null
  }
}

// 处理通知弹窗确认
function handleNotificationConfirm() {
  showNotificationModal.value = false
  // 只有在试看结束或权限相关错误时才跳转到直播列表页
  if (notificationMessage.value.includes('코인부족으로 라이브 입장이 불가합니다')) {
    router.replace('/live')
  } else if (notificationMessage.value.includes('시청이 종료되었습니다')) {
    router.replace('/live')
  }
}


// 结束观看（有积分用户）
async function endWatching() {
  if (!route.params.id) return
  try {
    const res = await api.post(`/api/live/rooms/${route.params.id}/end-watching`)
    if (res.ok) {
      notificationMessage.value = '시청이 종료되었습니다. 감사합니다!'
      showNotificationModal.value = true
    } else {
      const err = await res.json().catch(()=>({}))
      console.error('결束观看失败，状态码:', res.status, '错误信息:', err)
      notificationMessage.value = err?.error || '시청 종료 실패'
      showNotificationModal.value = true
    }
  } catch (e: any) {
    console.error('결束观看실패', e?.message || e)
    notificationMessage.value = '시청 종료 실패'
    showNotificationModal.value = true
  }
}

// 视频播放结束事件处理
function onVideoEnded() {
  if (hasPoints.value) {
    // 有积分用户：视频播放完成后自动结束观看
    endWatching()
  }
  // 无积分用户的试看倒计时会自动处理踢出逻辑，不需要在这里处理
}

// 移除fetchGifts函数，不再需要获取礼物列表

// 启动心跳
function startHeartbeat() {
  stopHeartbeat()
  sendHeartbeat()
  heartbeatTimer.value = setInterval(sendHeartbeat, HEARTBEAT_INTERVAL_MS)
}

function stopHeartbeat() {
  if (heartbeatTimer.value) clearInterval(heartbeatTimer.value)
}

async function sendHeartbeat() {
  if (!route.params.id) return
  try {
    const res = await api.post(`/api/live/rooms/${route.params.id}/viewers/heartbeat`)
    if (!res.ok) {
      const err = await res.json().catch(()=>({}))
      const msg = err?.error || '心跳失败'
      if (msg.includes('체험 시청이 종료되었습니다') ||
          msg.includes('시청이 종료되었습니다') ||
          msg.includes('하나의 라이브 방만 선택하여 시청할 수 있습니다')) {
        notificationMessage.value = '코인부족으로 라이브 입장이 불가합니다'
        showNotificationModal.value = true
        return
      }
      throw new Error(msg)
    }
  } catch (e: any) {
    console.error('心跳失败', e?.message || e)
  }
}




// 移除sendGiftApi函数，用户不再能发送礼物

const goBack = () => {
  router.push('/live')
}

const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 发送聊天消息
async function sendMessage() {
  const text = inputText.value.trim()
  if (!text) return

  try {
    const res = await api.post(`/api/live/rooms/${route.params.id}/messages`, { content: text })
    if (!res.ok) {
      const err = await res.json().catch(() => ({}))
      throw new Error(err?.error || '发送失败')
    }
    inputText.value = ''
    // 消息会通过SSE自动添加到列表中
  } catch (e: any) {
    notificationMessage.value = e?.message || '메시지 전송 실패'
    showNotificationModal.value = true
  }
}

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}
</script>

<template>
  <div class="layout" v-if="auth.user">
    <AppHeader />
    <div class="live-room" v-if="!loading && liveRoom">
      <!-- 左侧视频区域 -->
      <div class="video-section">
        <!-- 返回按钮 -->
        <div class="video-header">
          <button class="back-btn" @click="goBack">
            ← 라이브 목록으로 돌아가기
          </button>
        </div>

        <!-- 视频容器与覆盖信息条 -->
        <div class="video-container">
          <!-- 半透明信息条覆盖层 -->
          <div class="video-overlay-info">
            <div class="overlay-left">
              <h1 class="video-title">{{ liveRoom.title || liveRoom.channel.name }}</h1>
              <p class="video-channel">{{ liveRoom.channel.name }}</p>
            </div>
            <div class="overlay-right">
              <div class="online-indicator">
                <span class="online-dot"></span>
                <span class="online-text">{{ onlineCount }}명 온라인</span>
              </div>
              <!-- 试看倒计时提示 -->
              <div v-if="trialActive" class="trial-notice">
                체험 시청 남은 시간: {{ trialCountdown }}초
              </div>
              <!-- 有积分用户的结束观看按钮 -->
              <div v-if="canEndWatching" class="end-watching">
                <button class="end-btn" @click="endWatching">
                  시청 종료
                </button>
              </div>
            </div>
          </div>

          <!-- 视频播放器 -->
          <video
            v-if="liveRoom.replayVideo?.fileUrl"
            :src="toAbsoluteUrl(liveRoom.replayVideo.fileUrl)"
            autoplay
            muted
            playsinline
            webkit-playsinline
            class="video-player"
            :poster="toAbsoluteUrl(liveRoom.replayVideo.coverUrl) || undefined"
            @ended="onVideoEnded"
          >
            您的浏览器不支持视频播放
          </video>
          <div v-else class="no-video">
            <p>暂无视频内容</p>
          </div>
        </div>

        <!-- 频道信息卡片 -->
        <div class="channel-info-card">
          <img
            :src="toAbsoluteUrl(liveRoom.channel.avatarUrl) || 'https://picsum.photos/60'"
            :alt="liveRoom.channel.name"
            class="channel-avatar"
          />
          <div class="channel-details">
            <h3>{{ liveRoom.channel.name }}</h3>
            <p>{{ liveRoom.channel.description || '설명이 없습니다' }}</p>
          </div>
          <div class="channel-stats">
            <div class="stat-item">
              <span class="stat-label">시청</span>
              <span class="stat-value">{{ onlineCount }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-section">
        <div class="chat-header">
          <h3>채팅방</h3>
          <span class="online-count">{{ onlineCount }}명 온라인</span>
        </div>

        <div class="messages-container" ref="messagesContainer">
          <div
            v-for="message in messages"
            :key="message.id"
            class="message"
            :class="{
              'system-message': message.isSystem,
              'gift-message': message.isGift
            }"
          >
            <img :src="message.avatar" :alt="message.username" class="message-avatar" />
            <div class="message-content">
              <div class="message-header">
                <span class="username">{{ message.username }}</span>
                <span class="timestamp">{{ formatTime(message.timestamp) }}</span>
              </div>
              <div class="message-text">{{ message.content }}</div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <input
            type="text"
            v-model="inputText"
            placeholder="메시지 입력..."
            class="message-input"
            @keyup.enter="sendMessage"
          />
          <button class="send-btn" @click="sendMessage" :disabled="!inputText.trim()">
            전송
          </button>
        </div>
      </div>
    </div>

    <div v-else-if="loading" class="loading">
      <p>로딩 중...</p>
    </div>
  </div>

  <!-- 通知弹窗 -->
  <NotificationModal
    v-model="showNotificationModal"
    :title="notificationTitle"
    :message="notificationMessage"
    @confirm="handleNotificationConfirm"
  />
</template>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-bg);
}

.live-room {
  flex: 1;
  display: grid;
  grid-template-columns: 1fr 380px;
  grid-template-rows: 1fr; /* 确保行高度固定 */
  gap: var(--spacing-lg);
  padding: 0 var(--spacing-base);
  min-height: 0;
  height: calc(100vh - 90px); /* 固定总高度，减去头部高度 */
  overflow: hidden; /* 防止内容溢出 */
}

.video-section {
  display: flex;
  flex-direction: column;
  min-width: 0;
  overflow: hidden;
}

.video-header {
  padding: var(--spacing-base) var(--spacing-lg);
}

.back-btn {
  background: var(--color-surface);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  padding: 12px 20px;
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: var(--text-sm);
  font-weight: 500;
  box-shadow: var(--shadow-sm);
}

.back-btn:hover {
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.video-container {
  position: relative;
  flex: 1;
  background: linear-gradient(135deg, var(--color-surface) 0%, var(--color-surface-light) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  border-radius: var(--radius-lg);
  overflow: hidden;
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--color-border);
}

.video-overlay-info {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.6) 0%, rgba(0, 0, 0, 0.2) 70%, transparent 100%);
  padding: var(--space-4);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.overlay-left .video-title {
  color: #fff;
  margin: 0 0 4px 0;
  font-size: var(--text-lg);
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.overlay-left .video-channel {
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  font-size: var(--text-sm);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.overlay-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: var(--spacing-xs);
}

.online-indicator {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  background: rgba(0, 0, 0, 0.4);
  padding: 4px var(--spacing-xs);
  border-radius: var(--radius-sm);
}

.online-dot {
  width: 8px;
  height: 8px;
  background: #10b981;
  border-radius: 50%;
  animation: pulse-dot 2s infinite;
}

@keyframes pulse-dot {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.online-text {
  color: #fff;
  font-size: var(--text-xs);
  font-weight: 500;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-video {
  color: var(--color-text-muted);
  text-align: center;
  font-size: var(--text-base);
  background: var(--color-surface);
  padding: var(--space-8);
  border-radius: var(--radius-md);
  border: 2px dashed var(--color-border);
}

.channel-info-card {
  background: white;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding: var(--space-4);
  margin-top: var(--space-3);
  display: flex;
  align-items: center;
  gap: var(--space-3);
  box-shadow: var(--shadow-sm);
  transition: all 0.2s ease;
}

.channel-info-card:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-1px);
}

.channel-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid var(--color-border);
  flex-shrink: 0;
  box-shadow: var(--shadow-sm);
}

.channel-details {
  flex: 1;
  min-width: 0;
}

.channel-details h3 {
  color: var(--color-text);
  margin: 0 0 4px 0;
  font-size: var(--text-base);
  font-weight: 600;
}

.channel-details p {
  color: var(--color-text-muted);
  margin: 0;
  font-size: var(--text-sm);
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.channel-stats {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-label {
  color: var(--color-text-muted);
  font-size: var(--text-xs);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-value {
  color: var(--color-text);
  font-size: var(--text-sm);
  font-weight: 600;
}

.chat-section {
  background: white;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--color-border);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%; /* 使用100%高度，由网格布局控制 */
  max-height: 100%; /* 确保不超出网格分配的高度 */
}

.chat-header {
  position: sticky;
  top: 0;
  z-index: 5;
  padding: var(--space-4);
  border-bottom: 1px solid var(--color-border);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  backdrop-filter: blur(8px);
}

.chat-header h3 {
  color: var(--color-text);
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.online-count {
  color: var(--color-text-muted);
  font-size: 12px;
  background: var(--color-surface);
  padding: 4px 8px;
  border-radius: var(--radius-full);
  border: 1px solid var(--color-border);
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: var(--space-4);
  min-height: 200px; /* 设置最小高度确保有滚动空间 */
  max-height: calc(100vh - 250px); /* 设置具体的最大高度 */
  background: var(--color-surface-light);
}

.messages-container > * {
  margin-bottom: var(--space-3);
}

.messages-container > *:last-child {
  margin-bottom: 0;
}

.message {
  display: flex;
  gap: var(--space-2);
  padding: var(--space-3);
  border-radius: var(--radius-lg);
  background: white;
  border: 1px solid var(--color-border);
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.message:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-1px);
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
  border: 2px solid var(--color-border);
  box-shadow: var(--shadow-sm);
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2px;
}

.username {
  color: var(--color-text);
  font-size: var(--text-xs);
  font-weight: 600;
}

.timestamp {
  color: var(--color-text-muted);
  font-size: 10px;
}

.message-text {
  color: var(--color-text);
  font-size: var(--text-sm);
  line-height: 1.4;
  word-wrap: break-word;
}

.system-message {
  background: var(--color-warning-light);
  border-color: var(--color-warning);
}

.system-message .username {
  color: var(--color-warning);
}

.gift-message {
  background: linear-gradient(135deg, var(--color-accent-light), var(--color-accent));
  border-color: var(--color-accent);
}

.gift-message .message-text {
  color: var(--color-text);
  font-weight: 600;
}

.chat-input {
  display: flex;
  gap: var(--space-2);
  padding: var(--space-4);
  border-top: 1px solid var(--color-border);
  background: white;
}

.message-input {
  flex: 1;
  padding: 12px 16px;
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-full);
  color: var(--color-text);
  font-size: 14px;
  transition: all 0.2s;
}

.message-input:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px color-mix(in oklab, var(--color-primary) 20%, transparent);
}

.message-input::placeholder {
  color: var(--color-text-muted);
}

.send-btn {
  background: var(--color-primary);
  color: white;
  border: none;
  padding: 0 var(--space-4);
  border-radius: var(--radius-full);
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  height: 44px;
  transition: all 0.2s ease;
  box-shadow: var(--shadow-md);
  white-space: nowrap;
}

.send-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-btn:hover:not(:disabled) {
  background: color-mix(in oklab, var(--color-primary) 90%, black);
  box-shadow: var(--shadow-lg);
  transform: translateY(-1px);
}

/* 移除礼物相关样式，用户不再能发送礼物 */

.loading {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--color-text-muted);
  font-size: var(--text-base);
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 8px;
}

.messages-container::-webkit-scrollbar-track {
  background: var(--color-surface);
  border-radius: 4px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: var(--color-border);
  border-radius: 4px;
  border: 1px solid var(--color-surface);
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: var(--color-text-muted);
}

/* 隐藏任何可能残留的原生视频控件，确保无进度条显示 */
.video-player::-webkit-media-controls-enclosure { display: none !important; }
.video-player::-webkit-media-controls { display: none !important; }

/* ===========================================
   设计Token - 方案B统一视觉体系
   =========================================== */
:root {
  /* 圆角体系 */
  --radius-sm: 8px;
  --radius-md: 12px;

  /* 字体大小体系 */
  --text-xs: 12px;
  --text-sm: 14px;
  --text-base: 16px;
  --text-lg: 20px;
  --text-xl: 24px;

  /* 间距体系 */
  --spacing-xs: 8px;
  --spacing-sm: 12px;
  --spacing-base: 16px;
  --spacing-lg: 20px;
  --spacing-xl: 24px;

  /* 阴影层级 */
  --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.15);
  --shadow-md: 0 4px 16px rgba(0, 0, 0, 0.2);
  --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.25);

  /* 分隔线透明度 */
  --border-opacity: 0.15;
}

/* 试看倒计时样式 - 覆盖层版本 */
.video-overlay-info .trial-notice {
  background: var(--color-danger);
  color: white;
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-md);
  font-size: var(--text-sm);
  font-weight: bold;
  text-align: center;
  animation: pulse 1s infinite;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: var(--shadow-md);
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

/* 结束观看按钮样式 - 覆盖层版本 */
.video-overlay-info .end-watching {
  text-align: center;
}

.video-overlay-info .end-btn {
  background: var(--color-danger);
  color: white;
  border: none;
  padding: var(--space-2) var(--space-4);
  border-radius: var(--radius-md);
  cursor: pointer;
  font-size: var(--text-sm);
  font-weight: bold;
  transition: all 0.2s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: var(--shadow-md);
}

.video-overlay-info .end-btn:hover {
  background: color-mix(in oklab, var(--color-danger) 90%, black);
  transform: translateY(-1px);
  box-shadow: var(--shadow-lg);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .live-room {
    grid-template-columns: 1fr 320px;
    gap: var(--spacing-base);
  }
}

@media (max-width: 768px) {
  .layout {
    padding-bottom: 0;
  }

  .live-room {
    grid-template-columns: 1fr;
    grid-template-rows: auto 1fr;
    gap: 0;
    padding: 0;
    height: calc(100vh - 60px); /* 减少头部高度占用 */
  }

  .video-section {
    order: 1;
    padding: var(--spacing-xs);
  }

  .video-header {
    padding: var(--spacing-xs) 0;
  }

  .back-btn {
    padding: 8px 12px;
    font-size: 12px;
  }

  .video-container {
    /* 移动端优化：16:9 比例的直播间 */
    aspect-ratio: 16 / 9;
    min-height: auto;
    max-height: 50vh; /* 限制最大高度，避免占用过多屏幕 */
    width: 100%;
  }

  .video-player {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .video-overlay-info {
    padding: var(--spacing-xs);
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-xs);
  }

  .overlay-left {
    width: 100%;
  }

  .overlay-left .video-title {
    font-size: var(--text-sm);
    line-height: 1.3;
  }

  .overlay-left .video-channel {
    font-size: 11px;
  }

  .overlay-right {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .online-indicator {
    padding: 2px 6px;
  }

  .online-text {
    font-size: 10px;
  }

  .trial-notice {
    padding: 4px 8px;
    font-size: 11px;
  }

  .end-btn {
    padding: 4px 8px;
    font-size: 11px;
  }

  .channel-info-card {
    margin-top: var(--spacing-xs);
    padding: var(--spacing-sm);
    flex-direction: row;
    text-align: left;
    gap: var(--spacing-sm);
  }

  .channel-avatar {
    width: 40px;
    height: 40px;
  }

  .channel-details h3 {
    font-size: var(--text-sm);
    text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .channel-details p {
    font-size: 11px;
    text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .chat-section {
    order: 2;
    height: auto;
    max-height: calc(50vh - 60px); /* 聊天区域占用剩余空间 */
    min-height: 200px;
    margin: 0 var(--spacing-xs) var(--spacing-xs);
    border-radius: var(--radius-md);
  }

  .chat-header {
    padding: var(--spacing-sm);
  }

  .chat-header h3 {
    font-size: var(--text-sm);
  }

  .online-count {
    font-size: 10px;
    padding: 2px 6px;
  }

  .messages-container {
    padding: var(--spacing-sm);
    max-height: calc(50vh - 140px); /* 调整消息容器高度 */
  }

  .message {
    padding: var(--spacing-sm);
    margin-bottom: var(--spacing-sm);
  }

  .message-avatar {
    width: 28px;
    height: 28px;
  }

  .username {
    font-size: 11px;
  }

  .timestamp {
    font-size: 9px;
  }

  .message-text {
    font-size: 12px;
    line-height: 1.3;
  }

  .chat-input {
    padding: var(--spacing-sm);
    gap: var(--spacing-xs);
  }

  .message-input {
    padding: 8px 12px;
    font-size: 12px;
    height: 36px;
  }

  .send-btn {
    padding: 0 var(--spacing-sm);
    font-size: 12px;
    height: 36px;
  }
}

/* 超小屏幕优化 (iPhone SE 等) */
@media (max-width: 480px) {
  .live-room {
    height: calc(100vh - 50px);
  }

  .video-container {
    max-height: 45vh;
  }

  .chat-section {
    max-height: calc(55vh - 80px);
    min-height: 180px;
  }

  .messages-container {
    max-height: calc(55vh - 160px);
  }

  .video-overlay-info {
    padding: 6px;
  }

  .overlay-left .video-title {
    font-size: 12px;
  }

  .overlay-left .video-channel {
    font-size: 10px;
  }

  .channel-info-card {
    padding: 8px;
  }

  .channel-avatar {
    width: 32px;
    height: 32px;
  }

  .channel-details h3 {
    font-size: 12px;
  }

  .channel-details p {
    font-size: 10px;
  }
}

/* 横屏模式优化 */
@media (max-width: 768px) and (orientation: landscape) {
  .live-room {
    grid-template-columns: 1fr 280px;
    grid-template-rows: 1fr;
    height: calc(100vh - 50px);
  }

  .video-section {
    order: 1;
  }

  .chat-section {
    order: 2;
    max-height: 100%;
    margin: var(--spacing-xs);
  }

  .video-container {
    max-height: calc(100vh - 120px);
  }

  .messages-container {
    max-height: calc(100vh - 180px);
  }
}

/* 细节优化：滚动条美化 - 已移至上方统一定义 */

/* 加载状态优化 */
.loading {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: var(--text-base);
}

/* 微交互增强 */
.back-btn,
.gift-btn,
.end-btn {
  position: relative;
  overflow: hidden;
}

.back-btn::before,
.gift-btn::before,
.end-btn::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.3s ease, height 0.3s ease;
}

.back-btn:active::before,
.gift-btn:active::before,
.end-btn:active::before {
  width: 200px;
  height: 200px;
}
</style>
